package com.sky.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.aliyuncs.ecs.model.v20140526.DescribeClassicLinkInstancesResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountDisableException;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageBean;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.mindrot.jbcrypt.BCrypt;

import javax.xml.bind.annotation.XmlType;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return employee
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {

        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        //账号是否存在
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码是否正确
        //加密密码对比

        //password = DigestUtils.md5DigestAsHex(password.getBytes());//md5加密
        //BCrypt加密法
        //1、获取salt
        String password2=employee.getPassword();

        String key1 = "account:error:count:" + username;
        String key2 = "account:locked:" + username;

        ValueOperations valueOperations = redisTemplate.opsForValue();
        if (BCrypt.checkpw(password,password2)==false) {

            //如果有值，则证明已被锁定
            if (Boolean.TRUE.equals(redisTemplate.hasKey(key2))) {
                throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
            }
            if (redisTemplate.hasKey(key1)) {

                //前两次只需要更新状态
                if (Integer.valueOf((String) valueOperations.get(key1)) < 2) {
                    valueOperations.set(key1, "2", 0);//偏移量为0
                } else {
                    //第三次加锁
                    valueOperations.set(key2, "1", 1, TimeUnit.HOURS);
                    redisTemplate.delete(key1);
                }
            } else {
                //初始化
                valueOperations.set(key1, "1", 1, TimeUnit.MINUTES);
            }
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //账号锁定
        if (employee.getStatus() == StatusConstant.DISABLE) {
            throw new AccountDisableException(MessageConstant.ACCOUNT_DISABLE);
        }

        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();

        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置账号状态，默认正常状态 1表示正常 0表示锁定
        employee.setStatus(StatusConstant.ENABLE);

        //设置密码，默认123456
        //改为BCrypt 加密

        String salt = BCrypt.gensalt();
        String password = BCrypt.hashpw(PasswordConstant.DEFAULT_PASSWORD, salt);
        employee.setPassword(password);


        employeeMapper.insert(employee);
    }

    /**
     * 分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageBean page(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        return new PageBean(page.getTotal(), page.getResult());
    }

    /**
     * 启用禁用员工账号
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();

        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("******");
        return employee;
    }

    /**
     * 编辑员工信息
     *
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);
    }

    /**
     * 根据id获取权限
     * @param currentId
     * @return
     */
    @Override
    public List<String> getPermissionsById(Long currentId) {
        List<String> list=new ArrayList<>();
        List<Map<String,Object>> list2=employeeMapper.selectPermission(currentId);
        list2.forEach(map->{
            String permission = (String) map.get("permission");
            list.add(permission);
        });

        return list;
    }

    /**
     * 修改密码
     *
     * @param passwordEditDTO
     */
    @Override
    @Transactional
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        Employee employee = employeeMapper.getById(BaseContext.getCurrentId());
        String password = employee.getPassword();
        String oldPassword = passwordEditDTO.getOldPassword();
        //密码不对
        if(!BCrypt.checkpw(oldPassword,password)){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //密码正确，可以改密码
        String newPassword = passwordEditDTO.getNewPassword();
        String hashpw = BCrypt.hashpw(newPassword, BCrypt.gensalt());
        employee.setPassword(hashpw);
        employeeMapper.update(employee);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }


}
